import { TreeDataTranslate } from '@/utils/index';
import type { RouteRecordRaw } from 'vue-router';

// 自动化导入路由
const views = import.meta.glob('../views/**/*.vue');
const pages = import.meta.glob('../views/**/page.json', {
  eager: true,
  import: 'default'
});

interface PageConfig {
  parent?: string;
  [key: string]: any;
}

const routers = Object.entries(pages).map(([pagePath, config]: [string, any]) => {
  config = config as PageConfig;
  const path = pagePath.replace('../views', '').replace('/page.json', '');
  const name = pagePath.split('/').slice(-2, -1)[0];
  const compFunc = views[pagePath.replace('page.json', name + '.vue')];

  return {
    path: path,
    name: name,
    parent: config.parent || '',
    component: compFunc,
    meta: config
  };
});

// 转树结构
let routeList = TreeDataTranslate(routers, 'name', 'parent');
routeList.forEach(item => {
  if (item.children && item.children.length > 0) {
    item.redirect = { name: item.children[0].name };
  }
});
const result = routeList.sort((a, b) => a.meta.sort - b.meta.sort)

export default result;
